package com.global.college.base.baselist;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import android.view.ViewGroup;

import java.util.List;

/**
 * 类描述：主页面
 */

public class HsScrollViewPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> mFragment;
    private List<String> mTitle;
    private FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction;

    public HsScrollViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> mTitle) {
        super(fm);
        this.mFragment = fragments;
        this.mTitle = mTitle;
        mFragmentManager = fm;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (mTitle != null || mTitle.size() > 0)
            try {
                return mTitle.get(position);

            } catch (Exception e) {
                e.printStackTrace();
            }

        return super.getPageTitle(position);

    }

    @Override
    public Fragment getItem(int position) {
        return mFragment.get(position);
    }

    @Override
    public int getCount() {
        return mFragment != null ? mFragment.size() : 0;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        return super.instantiateItem(container, position);
    }

    /**
     * 清除缓存fragment
     *
     * @param container ViewPager
     */
    public void clear(ViewGroup container) {
        if (this.mCurTransaction == null) {
            this.mCurTransaction = this.mFragmentManager.beginTransaction();
        }

        for (int i = 0; i < mFragment.size(); i++) {
            long itemId = this.getItemId(i);
            String name = makeFragmentName(container.getId(), itemId);
            Fragment fragment = this.mFragmentManager.findFragmentByTag(name);
            if (fragment != null) {//根据对应的ID，找到fragment，删除
                mCurTransaction.remove(fragment);
            }
        }
        mCurTransaction.commitNowAllowingStateLoss();
    }

    /**
     * 等同于FragmentPagerAdapter的makeFragmentName方法，
     * 由于父类的该方法是私有的，所以在此重新定义
     *
     * @param viewId
     * @param id
     * @return
     */
    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }


}
